﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;

namespace SpotlessWeb.ActionResults
{
    public class CSVActionResult : ActionResult
    {

        public string[] ContentHeaders
        {
            get;
            set;
        }

        public List<string[]> Rows
        {
            get;
            set;
        }

        public Encoding ContentEncoding
        {
            get;
            set;
        }

        public string Name
        {
            get;
            set;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;

            response.ContentType = "text/csv";

            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }

            var fileName = "file.csv";

            if (Name.HasValue())
            {
                fileName = Name.Contains('.') ? Name : Name + ".csv";
                response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", fileName));
            }

            if (ContentHeaders != null && ContentHeaders.Length > 0)
            {
                response.Write(ContentHeaders.Select(x => string.Format("\"{0}\"", x)).StringConcat(","));
                response.Write(System.Environment.NewLine);
            }

            if (Rows != null)
            {
                foreach (string[] row in Rows)
                {
                    response.Write(row.StringConcat(x => string.Format("\"{0}\"", x), ","));
                    response.Write(System.Environment.NewLine);
                }
            }
        }
    }
}